package actionListener;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;

import miniMax.TicTacToeFramework;
import controller.Controlleriface;

public class SimpleListener implements ActionListener {

	private TicTacToeFramework model;
	private Controlleriface controller;

	public SimpleListener(TicTacToeFramework model, Controlleriface controller) {
		this.model = model;
		this.controller = controller;
	}

	public void actionPerformed(ActionEvent e) {
		JButton jb = (JButton) e.getSource();
		int idx = controller.getIndex(jb);
		boolean correctMove = model.setCharWithID(idx, controller.getActualPlayer().getPlayerChar(),true);
		if (correctMove) {
			int win = model.checkWin(idx);
			controller.setInput(idx);
			if (win == 1) {
				controller.setNameLabel(controller.getActualPlayer().getPlayerName()
						+ " hat gewonnen");
				controller.updateWins(win);
				controller.deactivate();
				controller.getView().getStart().setEnabled(true);
				controller.getView().getRestart().setEnabled(true);
			}else if(win == 0) {
				controller.setNameLabel("Unentschieden");
				controller.updateWins(win);
				controller.deactivate();
				controller.getView().getStart().setEnabled(true);
				controller.getView().getRestart().setEnabled(true);
			}
			else {
				controller.switchPlayer();
				controller.setNameLabel(controller.getActualPlayer().getPlayerName() + " ist dran.");
				controller.gameLoop();
			}

		}
	}
}
